/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 09 - 14
 * Time: 20:15
 */
//牛客 最长公共子序列(二)
public class Solution2 {
    String x = "";
    public String LCS (String s1, String s2) {
        x = s1;
        int m = s1.length();
        int n = s2.length();
        //dp[i][j]表示在s1中前i个字符与s2中前j个字符的最长公共子序列长度
        int[][] dp = new int[m + 1][n + 1];
        //记录动态规划数组相加的方向
        int[][] b = new int[m + 1][n + 1];
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n ; j++) {
                if(s1.charAt(i - 1) == s2.charAt(j - 1)) {
                    dp[i][j] = 1 + dp[i - 1][j - 1];
                    b[i][j] = 1;
                }else {
                    if(dp[i][j - 1] > dp[i - 1][j]) {
                        dp[i][j] = dp[i][j - 1];
                        b[i][j] = 2;
                    }else {
                        dp[i][j] = dp[i - 1][j];
                        b[i][j] = 3;
                    }
                }
            }
        }
        String ret = ans(m, n, b);
        if(ret.isEmpty()) return "-1";
        return ret;
    }
    private String ans(int i, int j, int[][] b) {
        String string = "";
        if(i == 0 || j == 0) return string;
        if(b[i][j] == 1) {
            string += ans(i - 1, j - 1, b);
            string += x.charAt(i - 1);
        }else if(b[i][j] == 2) {
            string += ans(i, j - 1, b);
        }else {
            string += ans(i - 1, j, b);
        }
        return string;
    }
}
